// jdbcsh - An interactive shell for JDBC databases
// Copyright (C) 2007 Dan Boitnott
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
        
package jdbcsh;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jline.ConsoleReader;

/**
 *
 * @author Dan Boitnott
 */
public class Main {

    private static ConsoleReader reader;
    private static final Dispatcher dsp = new Dispatcher();
    private static final Interpreter itp = new Interpreter(dsp);

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String l = "";

        initReader();
        itp.setReader(reader);

        while (true) {
            try {
                // Get the line
                l = reader.readLine(itp.getPrompt());
                reader.flushConsole();

                // Catch EOF
                if (l == null) {
                    break;
                }

                // Handle the line
                itp.handleLine(l);
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                die(1);
            } catch (Interpreter.InterpreterException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        die();
    }

    public static void die(int status) {
        System.out.print("Exiting\n");
        cleanReader();
        System.exit(status);
    }

    public static void die() {
        die(0);
    }

    private static void initReader() {
        try {
            reader = new ConsoleReader();
            reader.getTerminal().initializeTerminal();
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            die(1);
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            die(1);
        }
    }

    private static void cleanReader() {
        if (reader == null) return;
        reader.getTerminal().enableEcho();
    }
}
